package org.lc.stk.security.evaluator;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

/**
 * 资源权限评估器
 * 
 * &lt;p&gt;用于评估用户对特定资源的操作权限。支持以下权限格式：
 * ${资源类型}:${资源ID}:${操作}&lt;/p&gt;
 * 
 * &lt;p&gt;使用示例：
 * course:123:edit - 编辑ID为123的课程
 * bank:456:view - 查看ID为456的题库
 * paper:789:manage - 管理ID为789的试卷&lt;/p&gt;
 */
@Component
public class ResourcePermissionEvaluator {

    /**
     * 判断用户是否拥有对指定资源的特定操作权限
     *
     * @param authentication Spring Security认证对象
     * @param resourceType   资源类型(如course, bank, paper等)
     * @param resourceId     资源ID
     * @param action        操作类型(如edit, view, manage等)
     * @return 如果用户拥有权限返回true，否则返回false
     */
    public boolean hasPermission(
            Authentication authentication, 
            String resourceType,
            String resourceId, 
            String action) {
        
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        String requiredAuthority = String.format("%s:%s:%s", resourceType, resourceId, action);

        return authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> matchesAuthority(authority, requiredAuthority));
    }

    /**
     * 判断用户是否拥有对指定资源类型的全局操作权限
     * 
     * @param authentication Spring Security认证对象
     * @param resourceType   资源类型
     * @param action        操作类型
     * @return 如果用户拥有权限返回true，否则返回false
     */
    public boolean hasGlobalPermission(
            Authentication authentication, 
            String resourceType,
            String action) {
        
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        String requiredAuthority = String.format("%s:*:%s", resourceType, action);

        return authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> matchesAuthority(authority, requiredAuthority));
    }

    /**
     * 匹配权限字符串
     * 支持通配符"*"匹配任意资源ID
     */
    private boolean matchesAuthority(String grantedAuthority, String requiredAuthority) {
        if (grantedAuthority.equals(requiredAuthority)) {
            return true;
        }

        String[] grantedParts = grantedAuthority.split(":");
        String[] requiredParts = requiredAuthority.split(":");

        if (grantedParts.length != 3 || requiredParts.length != 3) {
            return false;
        }

        // 检查资源类型是否匹配
        if (!grantedParts[0].equals(requiredParts[0])) {
            return false;
        }

        // 检查资源ID是否匹配（支持通配符）
        if (!grantedParts[1].equals("*") && !grantedParts[1].equals(requiredParts[1])) {
            return false;
        }

        // 检查操作是否匹配
        return grantedParts[2].equals(requiredParts[2]);
    }
}